<?php
namespace yan\editor_frontend;
class Editor extends \yii\base\Component{
	public $widgets = [];
	public function run($params = []){
		$type = !empty($params['type']) ? $params['type'] : 'preview';
		$data = !empty($params['data']) ? $params['data'] : '';
		$id = !empty($params['id']) ? $params['id'] : '';
		$lang = !empty($params['lang']) ? $params['lang'] : 'zh-TW';
		$widgets = null;
		$editorClass = \yan\editor_frontend\editor\EditorWidget::class;
		switch ($type) {
			case 'release':
				$widgets = json_decode($data, true);
				if(empty($widgets)){
					// $xmlObject = simplexml_load_string($data);
					// $json = json_encode($xmlObject);
					// $widgets = json_decode($json, true);					
					if(!empty($data)){
						$dom = new \DOMDocument();
				        $dom->loadXML($data);
				        $widgets = $this->xmlToArray($dom->documentElement);
					}
					$editorClass = \yan\editor_frontend\editorxml\EditorWidget::class;
				}
			break;
			
			default:
				$data = Yii::$app->pageService->getPreview($id, $lang);
				$widgets = json_decode($data, true);
				if(empty($widgets)){
					// $xmlObject = simplexml_load_string($data);
					// $json = json_encode($xmlObject);
					// $widgets = json_decode($json, true);
					if(!empty($data)){
						$dom = new \DOMDocument();
				        $dom->loadXML($data);
				        $widgets = $this->xmlToArray($dom->documentElement);
					}
					$editorClass = \yan\editor_frontend\editorxml\EditorWidget::class;
				}
			break;
		}
		return $editorClass::widget([
			'type'=>$type,
			'data'=>$widgets,
			'widgets'=>$this->widgets,
		]);
	}

	public function xmlToArray($node) {
	    $array = array();	    
	    if ($node->hasAttributes()) {
	        $attributes = $node->attributes;
	        foreach ($attributes as $key => $attr) {
	            $array['@attributes'][$key] = $attr->nodeValue;
	        }
	    }
	    if ($node->hasChildNodes()) {
	        $children = $node->childNodes;
	        foreach ($children as $key=> $child) {
	            $array[$child->nodeName . '_'.$key] = $this->xmlToArray($child);
	        }
	    } else {
	        $array['nodeValue'] = $node->nodeValue;
	    }
	    return $array;
	}
}
